﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Transactions;
using Autofac;
using Autofac.Integration.Mvc;
using Bids.Core.Common.IO;
using Bids.Core.DomainObjects;
using Bids.Data;
using Bids.Service;
using Bids.Core.Common.Security;
using Bids.Web.Model;

namespace Bids.Web.Controllers
{
    [Authorize]
    public class DesignerController : Controller
    {
        IUserContext userContext = AutofacDependencyResolver.Current.RequestLifetimeScope.Resolve<IUserContext>();
        IRepository<Task> _iRpoTask;
        IRepository<Contribution> _iRpoContr;
        IRepository<ContributionItem> _iRpoContrItem;
        IUserContext _iUserContext;
        private IRepository<User> _iRpoUser;
        private IRepository<InBox> _iRpoInBox;
        private IRepository<Finance> _iRpoFinance;
        private IRepository<WithdrawDeposit> _iRpoWithdrawDeposit;
        private IRepository<News> _iRpoNews;
        private IRepository<Help> _iRoHelp;
        private IRepository<Mood> _iRoMood;
        private IRepository<MoodReply> _repository;
        private IRepository<Plane> _iRoPlane;
        private IRepository<DesignerCase> _iRoDesignerCase;
        public DesignerController(IRepository<Task> iRpoTask
            , IRepository<Contribution> iRpoContr
            , IRepository<ContributionItem> iRpoContrItem
            , IUserContext iUserContext
            , IRepository<User> iRpoUser
            , IRepository<InBox> iRpoInBox
            , IRepository<Finance> iRpoFinance
            , IRepository<WithdrawDeposit> iRpoWithdrawDeposit
            , IRepository<News> iRpoNews
            , IRepository<Help> iRoHelp
            , IRepository<Mood> iRoMood
            , IRepository<MoodReply> repository
            , IRepository<Plane> iRoPlane
            , IRepository<DesignerCase> iRoDesignerCase
            )
        {
            _iRpoTask = iRpoTask;
            _iRpoContr = iRpoContr;
            _iRpoContrItem = iRpoContrItem;
            _iUserContext = iUserContext;
            _iRpoUser = iRpoUser;
            _iRpoInBox = iRpoInBox;
            _iRpoFinance = iRpoFinance;
            _iRpoWithdrawDeposit = iRpoWithdrawDeposit;
            _iRpoNews = iRpoNews;
            _iRoHelp = iRoHelp;
            _iRoMood = iRoMood;
            _repository = repository;
            _iRoPlane = iRoPlane;
            _iRoDesignerCase = iRoDesignerCase;
        }
        //设计师大厅
        public ActionResult Index(int page = 20)
        {
            DesignerModel model = new DesignerModel();
            model.Users = _iRpoUser.Find(userContext.User.ID);
            //投标
            model.tenders = _iRpoContr.Where(t => t.DesignerId == userContext.User.ID)
                      .Select(t => t.Task).Count();
            //入围
            model.Finalist = _iRpoContr.Where(
               t => t.DesignerId == userContext.User.ID && t.Finalist == true)
                                .Select(t => t.Task).Count();
            //中标
            model.WinTheBidding = _iRpoContr.Where(
                t => t.DesignerId == userContext.User.ID && t.Status == (int)ContributionStatus.已截稿)
                                 .Select(t => t.Task).Count();
            //佣金总额
            var sum =
                _iRpoFinance.Where(t => t.UserId == userContext.User.ID && t.State == 2 && t.Type == 1)
                            .Sum(s => s.Amount);
            model.MoneyCount = sum;
            //佣金余额
            int fu = _iRpoFinance.Where(t => t.UserId == userContext.User.ID && t.State == 2 && t.Type == 2 || t.State == 1).Sum(t => t.Amount);
            if (sum > 0)
            {
                int mysum = sum - fu;
                if (mysum > 0)
                {
                    model.Money = mysum;
                }
                else
                {
                    model.Money = 0;
                }
            }
            //网站新闻
            model.Newses = _iRpoNews.Where(t => true).OrderByDescending(t => t.CreateTime).Take(2).ToList();
            //设计须知
            model.Helps = _iRoHelp.Where(t => true).OrderByDescending(t => t.CreateTime).Take(5).ToList();
            //收入排行
            //user表.select(t=>new {name = t.nickname,amount = t.财务表.where(d=>d.state==2).sum(d=>d.amount)}).orderbydesc(t=>t.amount)
            var user = _iRpoUser.Where(t => true);
            var myuser = user.Select(t => new { name = t.NickName, amount = t.Finances.Where(d => d.State == 2 && t.Type == 1).Sum(d => d.Amount) })
                .OrderByDescending(t => t.amount).Take(10);
            List<myusers> list = new List<myusers>();
            if (myuser != null)
            {
                foreach (var item in myuser)
                {
                    if (item.name != null && item.amount != 0)
                    {
                        list.Add(new myusers() { name = item.name, amount = item.amount });
                    }

                }
            }
            model.Myuserses = list;
            //网站动态
            model.Trends = _iRpoContr.Where(t => t.Finalist == true || t.Status == (int)ContributionStatus.已截稿).OrderByDescending(t => t.CreateTime).Take(page);
            //短文
            int pageSize = _iRoMood.Where(t => true).OrderByDescending(t => t.CreateTime).Count();
            if (pageSize > page)
            {
                model.Moods = _iRoMood.Where(t => true).OrderByDescending(t => t.CreateTime).Take(page);
            }
            else
            {
                model.Moods = _iRoMood.Where(t => true).OrderByDescending(t => t.CreateTime);
            }
            if (pageSize - 10 > page)
            {
                ViewBag.Page = page + 10;
            }
            else
            {
                ViewBag.Page = page;
            }
            return View(model);
        }
        //评论
        public string PinLun(MoodReply moodReply)
        {
            moodReply.CreateTime = DateTime.Now;
            _repository.Add(moodReply);
            return "ok";
        }
        //短文
        public string Moods(Mood mood)
        {
            mood.CreateTime = DateTime.Now;
            _iRoMood.Add(mood);
            return "ok";
        }
        //回复
        public string HueiFu(MoodReply moodReply)
        {
            moodReply.CreateTime = DateTime.Now;
            _repository.Add(moodReply);
            return "ok";
        }
        public ActionResult Contribute(int taskId, int? ContributionId)
        {
            var task = _iRpoTask.Find(taskId);
            if (task.Contributions.Where(t => t.DesignerId == _iUserContext.User.ID).Count() >= 3)
            {
                TempData["error"] = "你已经提交了3个作品了，不能再提交了";
                return View(task);
            }
            return View(task);
        }
        [HttpPost]
        public ActionResult Contribute(int taskId, int? ContributionId, FormCollection form)
        {
            var task = _iRpoTask.Find(taskId);
            if (task.Contributions.Where(t => t.DesignerId == _iUserContext.User.ID).Count() >= 3)
            {
                TempData["error"] = "你已经提交了3个作品了，不能再提交了";
                return View(task);
            }
            using (TransactionScope ts = new TransactionScope())
            {
                Contribution contr = null;

                if (ContributionId.HasValue)
                {
                    contr = _iRpoContr.Find(ContributionId.Value);
                }
                else
                {
                    contr = new Contribution
                    {
                        TaskId = taskId,
                        CreateTime = DateTime.Now,
                        Status = (int)ContributionStatus.已投稿,
                        DesignerId = _iUserContext.User.ID,
                        Title = form["Title"].Trim()
                    };
                    _iRpoContr.Add(contr);

                }
                var item = new ContributionItem
                    {
                        Contribution = contr,
                        Logo = form["LOGO"].Trim(),
                        CreateTime = DateTime.Now,
                        Explain = form["Explain"]
                    };
                _iRpoContrItem.Add(item);
                ts.Complete();
            }
            TempData["msg"] = "作品提交成功";
            return View(task);
        }
        //个人信息
        public ActionResult Info()
        {
            InfoModel model = new InfoModel();
            model.User = _iRpoUser.Find(userContext.User.ID);
            var isplane = _iRoPlane.Where(t => t.UserId == userContext.User.ID).FirstOrDefault();
            if (isplane == null)
            {
                _iRoPlane.Add(new Plane() { UserId = userContext.User.ID });
            }
            model.Sign = _iRoPlane.Where(t => t.Sign != 0).Count();
            model.Brand = _iRoPlane.Where(t => t.Brand != 0).Count();
            model.Cartoon = _iRoPlane.Where(t => t.Cartoon != 0).Count();
            model.Posters = _iRoPlane.Where(t => t.Posters != 0).Count();
            model.PictureAlbum = _iRoPlane.Where(t => t.PictureAlbum != 0).Count();
            model.Pacr = _iRoPlane.Where(t => t.Pacr != 0).Count();
            model.ShopSign = _iRoPlane.Where(t => t.ShopSign != 0).Count();
            model.Web = _iRoPlane.Where(t => t.Web != 0).Count();
            model.Flash = _iRoPlane.Where(t => t.Flash != 0).Count();
            model.Interface = _iRoPlane.Where(t => t.Interface != 0).Count();
            model.AllWeb = _iRoPlane.Where(t => t.AllWeb != 0).Count();
            model.Banner = _iRoPlane.Where(t => t.Banner != 0).Count();
            model.TaoBao = _iRoPlane.Where(t => t.TaoBao != 0).Count();
            model.Order = _iRoPlane.Where(t => t.Order != 0).Count();
            model.WebUpdate = _iRoPlane.Where(t => t.WebUpdate != 0).Count();
            model.Plane = isplane;
            return View(model);
        }
        public ActionResult ajaxInfo(string labelid, int price)
        {
            var u = _iRoPlane.Where(t => t.UserId == userContext.User.ID).FirstOrDefault();
            if (labelid == "Sign") { u.Sign = price; }
            if (labelid == "Brand") { u.Brand = price; }
            if (labelid == "Cartoon") { u.Cartoon = price; }
            if (labelid == "Posters") { u.Posters = price; }
            if (labelid == "PictureAlbum") { u.PictureAlbum = price; }
            if (labelid == "Pacr") { u.Pacr = price; }
            if (labelid == "ShopSign") { u.ShopSign = price; }
            if (labelid == "Web") { u.Web = price; }
            if (labelid == "Flash") { u.Flash = price; }
            if (labelid == "Interface") { u.Interface = price; }
            if (labelid == "AllWeb") { u.AllWeb = price; }
            if (labelid == "Banner") { u.Banner = price; }
            if (labelid == "TaoBao") { u.TaoBao = price; }
            if (labelid == "Order") { u.Order = price; }
            if (labelid == "WebUpdate") { u.WebUpdate = price; }
            UpdateModel(u);
            _iRoPlane.Update(u);
            return Content("ok");
        }
        [HttpGet]
        public ActionResult Info_Edit()
        {

            InfoModel model = new InfoModel();
            model.User = _iRpoUser.Find(userContext.User.ID);
            var isplane = _iRoPlane.Where(t => t.UserId == userContext.User.ID).FirstOrDefault();
            if (isplane == null)
            {
                _iRoPlane.Add(new Plane() { UserId = userContext.User.ID });
            }
            model.Sign = _iRoPlane.Where(t => t.Sign != 0).Count();
            model.Brand = _iRoPlane.Where(t => t.Brand != 0).Count();
            model.Cartoon = _iRoPlane.Where(t => t.Cartoon != 0).Count();
            model.Posters = _iRoPlane.Where(t => t.Posters != 0).Count();
            model.PictureAlbum = _iRoPlane.Where(t => t.PictureAlbum != 0).Count();
            model.Pacr = _iRoPlane.Where(t => t.Pacr != 0).Count();
            model.ShopSign = _iRoPlane.Where(t => t.ShopSign != 0).Count();
            model.Web = _iRoPlane.Where(t => t.Web != 0).Count();
            model.Flash = _iRoPlane.Where(t => t.Flash != 0).Count();
            model.Interface = _iRoPlane.Where(t => t.Interface != 0).Count();
            model.AllWeb = _iRoPlane.Where(t => t.AllWeb != 0).Count();
            model.Banner = _iRoPlane.Where(t => t.Banner != 0).Count();
            model.TaoBao = _iRoPlane.Where(t => t.TaoBao != 0).Count();
            model.Order = _iRoPlane.Where(t => t.Order != 0).Count();
            model.WebUpdate = _iRoPlane.Where(t => t.WebUpdate != 0).Count();
            model.Plane = isplane;
            return View(model);
        }
        [HttpPost]
        public ActionResult Info_Edit(User user)
        {
            var u = _iRpoUser.Find(user.ID);
            UpdateModel(u);
            _iRpoUser.Update(u);
            return RedirectToAction("Info", "Designer");
        }
        //嵌套上传
        public ActionResult Ups(int login)
        {
            ViewBag.login = login;
            return View();
        }

        public ActionResult isNickName(string NickName)
        {
            NickName = NickName.Trim().Replace(" ", "");
            if (string.IsNullOrEmpty(NickName))
            {
                //请输入用户名
                return Content("1");
            }
            var login = _iRpoUser.Find(userContext.User.ID);
            if (login.NickName == NickName)
            {
                //您的用户名未做更改
                return Content("2");
            }
            if (_iRpoUser.Find(t => t.ID != userContext.User.ID && t.NickName == NickName) != null)
            {
                //改用户名已经存在，请重新设置
                return Content("3");
            }
            login.NickName = NickName;
            _iRpoUser.Update(login);

            return Content(NickName);
        }
        [HttpPost]
        public ActionResult Info(FormCollection form)
        {

            return View();
        }
        public ActionResult Message()
        {
            var message = _iRpoInBox.Where(t => t.UserId == userContext.User.ID);
            return View(message);
        }
        public ActionResult Message_Delete(int id)
        {
            var lis = _iRpoInBox.Find(id);
            _iRpoInBox.Remove(lis);
            TempData["Message"] = "删除成功";
            return RedirectToAction("Message");
        }
        public ActionResult Message_Delete_List(string idlist)
        {
            List<int> list = splitString(idlist);
            var mylist = _iRpoInBox.Where(t => list.Contains(t.ID));
            _iRpoInBox.Remove(mylist);
            TempData["Message"] = "删除成功";
            return RedirectToAction("Message");
        }
        public ActionResult Message_update_read(int r, string idlist)
        {
            List<int> list = splitString(idlist);
            var mylist = _iRpoInBox.Where(t => list.Contains(t.ID));
            if (r == 1)
            {
                foreach (var inBox in mylist)
                {
                    inBox.State = 1;
                    _iRpoInBox.Update(inBox);
                }
            }
            else
            {
                foreach (var inBox in mylist)
                {
                    inBox.State = 2;
                    _iRpoInBox.Update(inBox);
                }
            }
            TempData["Message"] = "更新成功";
            return RedirectToAction("Message");
        }
        public ActionResult SelectMessage(int id)
        {
            var list = _iRpoInBox.Where(t => t.ID == id);
            var Data = from m in list
                       select new { m.Sender, m.Title, m.Content };

            return Json(Data, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Commission()
        {
            var list = _iRpoFinance.Where(t => t.UserId == userContext.User.ID).OrderByDescending(t => t.CreateTime);
            return View(list);
        }
        public ActionResult Payment()
        {
            var sum =
                _iRpoFinance.Where(t => t.UserId == userContext.User.ID && t.State == 2 && t.Type == 1)
                            .Sum(s => s.Amount);
            int fu = _iRpoFinance.Where(t => t.UserId == userContext.User.ID && t.State == 2 && t.Type == 2 || t.State == 1).Sum(t => t.Amount);
            if (sum > 0)
            {
                ViewBag.sum = sum - fu;
            }
            else
            {
                ViewBag.sum = 0;
            }
            User user = _iRpoUser.Find(userContext.User.ID);
            ViewBag.Brank = user.Brank;
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Payment_Edit(string Bank)
        {
            var sum =
                _iRpoFinance.Where(t => t.UserId == userContext.User.ID && t.State == 2 && t.Type == 1)
                            .Sum(s => s.Amount);
            int fu = _iRpoFinance.Where(t => t.UserId == userContext.User.ID && t.State == 2 && t.Type == 2 || t.State == 1).Sum(t => t.Amount);
            if (sum > 0)
            {
                int mysum = sum - fu;
                if (mysum > 0)
                {
                    WithdrawDeposit wd = new WithdrawDeposit()
                        {
                            UserId = userContext.User.ID,
                            State = 1,
                            Amount = mysum,
                            CashInfo = Bank
                        };
                    _iRpoWithdrawDeposit.Add(wd);
                    Finance f = new Finance()
                        {
                            UserId = userContext.User.ID,
                            Amount = mysum,
                            Type = 2,
                            CreateTime = DateTime.Now,
                            State = 1
                        };
                    _iRpoFinance.Add(f);
                    TempData["Message"] = "申请成功";
                }
                else
                {
                    TempData["Message"] = "账号已没现金";
                }
            }
            return RedirectToAction("Payment");
        }
        public ActionResult Main()
        {
            MainModel model = new MainModel();
            model.Users = _iRpoUser.Where(t => t.ID == userContext.User.ID).FirstOrDefault();
            model.DesignerCases = _iRoDesignerCase.Where(t => t.UserId == userContext.User.ID);
            return View(model);
        }
        public ActionResult DesignerMain(int id)
        {
            MainModel model = new MainModel();
            model.Users = _iRpoUser.Where(t => t.ID == id).FirstOrDefault();
            model.DesignerCases = _iRoDesignerCase.Where(t => t.UserId == id);
            return View(model);
        }
        public ActionResult UpdateCate(string Img)
        {
            DesignerCase designerCase = new DesignerCase()
                {
                    CreateTime = DateTime.Now,
                    Img = Img,
                    UserId = userContext.User.ID
                };
            _iRoDesignerCase.Add(designerCase);
            return Content("ok");
        }
        /// <summary>
        /// 参与的
        /// </summary>
        /// <returns></returns>
        public ActionResult Projects()
        {
            var task = _iRpoContr.Where(t => t.DesignerId == userContext.User.ID)
                      .Select(t => t.Task);
            return View(task);
        }
        /// <summary>
        /// 入围
        /// </summary>
        /// <returns></returns>
        public ActionResult Projects1()
        {
            var task = _iRpoContr.Where(
                t => t.DesignerId == userContext.User.ID && t.Finalist == true)
                                 .Select(t => t.Task);
            return View(task);
        }
        public ActionResult Projects2()
        {
            var task = _iRpoContr.Where(
               t => t.DesignerId == userContext.User.ID && t.Status == (int)ContributionStatus.已截稿)
                                .Select(t => t.Task);
            return View(task);
        }
        public ActionResult Changepwd()
        {
            _iRpoTask.Where(t => t.Designer.ID == userContext.User.ID);
            return View();
        }
        public string checkpwd(string oldpassword)
        {
            string returns = "旧密码错误";
            if (_iUserContext.User.Login.Password.ToLower() == oldpassword.ToMD5().ToLower())
            {
                returns = "true";
            }
            return returns;
        }
        [HttpPost]
        public ActionResult Changepwd(string oldpassword, string password, string password1)
        {
            if (_iUserContext.User.Login.Password.ToLower() != oldpassword.ToMD5().ToLower())
            {
                TempData["Message"] = "旧密码不正确,请重新输入";
            }
            else if (password.Trim().ToLower() != password1.Trim().ToLower())
            {
                TempData["Message"] = "两次输入的密码不一致,请重新输入";
            }
            else
            {
                var u = _iRpoUser.Where(t => t.ID == userContext.User.ID).FirstOrDefault();
                u.Login.Password = password1.Trim().ToMD5();
                _iRpoUser.Update(u);
                TempData["Message"] = "更新成功";
            }

            return View();
        }
        public List<int> splitString(string idlist)
        {
            List<int> list = new List<int>();
            string[] strings = idlist.Split(',');
            foreach (var s in strings)
            {
                list.Add(Convert.ToInt32(s));
            }
            return list;
        }

    }
}
